# Copyright 2016 The Closure Rules Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

def _web_library_external(ctx):
    """Downloads HTTP archive and creates a webfiles rule."""
    name = ctx.attr.generated_rule_name or ctx.name
    lines = ["# DO NOT EDIT: generated by webfiles_external()", ""]
    if ctx.attr.default_visibility:
        lines.append("package(default_visibility = %s)" % (
            ctx.attr.default_visibility
        ))
        lines.append("")
    lines.append("licenses(%s)" % repr(ctx.attr.licenses))
    lines.append("")
    lines.append("load(\"@io_bazel_rules_closure//closure:" +
                 "defs.bzl\", \"web_library\")")
    lines.append("")
    lines.append("web_library(")
    lines.append("    name = %s," % repr(name))
    if ctx.attr.path:
        lines.append("    path = %r," % ctx.attr.path)
    if ctx.attr.srcs:
        lines.append("    srcs = %s," % _repr_list(ctx.attr.srcs))
    else:
        lines.append("    srcs = glob(")
        lines.append("        %s," % _repr_list(ctx.attr.glob, indent = "        "))
        lines.append("        exclude = %s," %
                     _repr_list(
                         ctx.attr.exclude + ["BUILD", "WORKSPACE"],
                         indent = "        ",
                     ))
        lines.append("    ),")
    for attr in (
        "data",
        "visibility",
        "exports",
        "suppress",
        "deps",
    ):
        value = getattr(ctx.attr, attr, None)
        if value:
            lines.append("    %s = %s," % (attr, _repr_list(value)))
    if ctx.attr.testonly_:
        lines.append("    testonly = 1,")
    lines.append(")")
    lines.append("")
    extra = ctx.attr.extra_build_file_content
    if extra:
        lines.append(extra)
        if not extra.endswith("\n"):
            lines.append("")
    ctx.download_and_extract(
        ctx.attr.urls,
        "",
        ctx.attr.sha256,
        "",
        ctx.attr.strip_prefix,
    )
    ctx.file("BUILD", "\n".join(lines))

def _repr_list(items, indent = "    "):
    items = sorted(items)
    if not items:
        return "[]"
    if len(items) == 1:
        return repr(items)
    parts = [repr(item) for item in items]
    return (("[\n%s    " % indent) +
            (",\n%s    " % indent).join(parts) +
            (",\n%s]" % indent))

web_library_external = repository_rule(
    implementation = _web_library_external,
    attrs = {
        "sha256": attr.string(mandatory = True),
        "urls": attr.string_list(mandatory = True, allow_empty = False),
        "licenses": attr.string_list(mandatory = True, allow_empty = False),
        "strip_prefix": attr.string(),
        "path": attr.string(mandatory = True),
        "srcs": attr.string_list(),
        "glob": attr.string_list(default = ["**"]),
        "exclude": attr.string_list(),
        "data": attr.string_list(allow_empty = False),
        "deps": attr.string_list(),
        "exports": attr.string_list(),
        "suppress": attr.string_list(),
        "testonly_": attr.bool(),
        "generated_rule_name": attr.string(),
        "default_visibility": attr.string_list(default = ["//visibility:public"]),
        "extra_build_file_content": attr.string(),
    },
)
